package coupon

import (
	// "bp/cache"
	"bp/conf"
	"bp/db"

	// "bgs/grpc/client"
	internalHttpMiddleware "bp/internal/middleware/http"
	"bp/internal/service/com"
	"bp/internal/service/entity"
	"bp/internal/twirpex"
	"go.uber.org/zap"

	// "bp/internal/util"
	couponGrpc "bp/rpc/gen/mwebapi/mcoupon"
	messageGrpc "bp/rpc/gen/shared/message"
	"context"

	"github.com/go-chi/chi"
	"github.com/golang/protobuf/ptypes/empty"
)

type CouponMWebApiImp struct {
	dao       *db.PgDao
	slog      *zap.SugaredLogger
	vars      *conf.VarsSection
	entityHub *entity.EntityHub
	comHub    *com.ComHub
	// cacher *cache.Adapter
	couponGrpc.CouponOpServiceServer
}

// New initialization
func New(
	slog *zap.SugaredLogger,
	pgdao *db.PgDao,
	vars *conf.VarsSection,
	entityHub *entity.EntityHub,
	comHub *com.ComHub,
	// adp *cache.Adapter,
) (ws *CouponMWebApiImp) {
	ws = &CouponMWebApiImp{
		dao:       pgdao,
		slog:      slog.With("module", "CouponMWebApi"),
		vars:      vars,
		entityHub: entityHub,
		comHub:    comHub,
		// cacher:           adp,
	}
	return
}

const (
	EntityName                       string = "优惠券"
	PingMethod                       string = "/coupon/ping/exec"            // GET
	GettingCouponMethod              string = "/coupon/{coupon_id}/getting"  // POST
	GetCouponMethod                  string = "/coupon/{coupon_id}"          // GET
	ListCouponWithStatsMethod        string = "/couponWithDistributionStats" // GET
	GetMemberCouponMethod            string = "/myCoupon/{id}"               // GET
	ListMemberCouponsMethod          string = "/myCoupons"                   // GET
	ListAvailableMemberCouponsMethod string = "/myAvailableCoupons"          // GET
)

// RegisterToWeb 将部分grpc方法注册到web
func (s *CouponMWebApiImp) RegisterToWeb(r chi.Router) {
	couponRT := twirpex.NewSingleTwirpServerProxy(couponGrpc.NewCouponOpServiceServer(s))

	r.Group(func(r chi.Router) {
		r.Get(PingMethod, couponRT.Handle("PingCoupon"))
		r.Group(func(r chi.Router) {
			r.Use(internalHttpMiddleware.WithAuthorizationToken(s.slog, s.vars))
			r.Post(GettingCouponMethod, couponRT.Handle("GettingCoupon"))
			r.Get(GetCouponMethod, couponRT.Handle("GetCoupon"))
			r.Get(GetMemberCouponMethod, couponRT.Handle("GetMemberCoupon"))
			r.Group(func(r chi.Router) {
				r.Use(internalHttpMiddleware.WithPager(s.slog, s.vars))
				r.Get(ListCouponWithStatsMethod, couponRT.Handle("ListCouponWithDistributionStats"))
				r.Get(ListMemberCouponsMethod, couponRT.Handle("ListMemberCoupons"))
				r.Get(ListAvailableMemberCouponsMethod, couponRT.Handle("ListAvailableMemberCoupons"))
			})
		})
	})
}

func (s *CouponMWebApiImp) PingCoupon(ctx context.Context, _ *empty.Empty) (res *messageGrpc.PingRes, err error) {
	res = &messageGrpc.PingRes{
		Msg: "coupon:ok",
	}
	return
}
